#include <iostream>
#include <cmath>

#include "src/image.h"

#include "contrib/Eigen/Dense"

#define cimg_display 0
#include "contrib/CImg/CImg.h"

using namespace cimg_library;
using namespace std;

int main(int argc, char** argv) {
    // Check unput
    if (argc != 2) {
        cerr << "Error: exactly 1 input parameter expected" << endl;
        return 1;
    }

    // Load cimg_image
    CImg<float> cimg_image;
    try {
        cimg_image.load(argv[1]);
    } catch (...) {
        cerr << "Unable to load image " << argv[1] << endl;
        return 1;
    }

    // Check cimg_image format
    if (cimg_image.depth() != 1 || cimg_image.spectrum() != 1) {
        cerr << "Wrong image format" << endl;
        return 1;
    }

    Image image(cimg_image.data(), cimg_image.width(), cimg_image.height());
    Image edges = EdgesMeasure<6>(image);
    Image cov = GetCovMatrix<6>(image);

    float sigma = GetLastEigenvalue<6>(cov);

    for (int i = 0; i < 3; ++i) {
        float tau = sigma * 81.8208;
        cov = GetCovMatrixByEdgesThrash<6>(image, edges, tau);
        if (cov.IsEmpty()) {
            break;
        }
        sigma = GetLastEigenvalue<6>(cov);
    }

    cout << sqrt(sigma) << endl;
}